package com.astrocsr.action.home;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.astrocsr.business.UserManager;
import com.astrocsr.common.helper.ContextHelper;
import com.astrocsr.domain.model.HomeModel;
import com.astrocsr.domain.web.UserInfo;
import com.opensymphony.xwork2.ModelDriven;

/**
 * 
 * @author Ho.Viet.Duan Created Jan 08, 2014
 */
@Controller("homeAction")
@Scope("prototype")
public class HomeAction extends BaseAction implements
		ModelDriven<HomeModel> {

	private static final long serialVersionUID = 1L;
	private HomeModel model = new HomeModel();

	public HomeModel getModel() {
		return model;
	}

	@Autowired
	private UserManager userManager;

	static final Logger log = Logger.getLogger(HomeAction.class);

	/**
	 * Change Password
	 */
	public String changePassword() throws Exception {
		try {

			log.info("changePassword:method");
			UserInfo userInfo = model.getUserInfo();
			if (userInfo != null && 
					validateChangingPassword(userInfo.getPasswordCur(), userInfo.getPasswordNew(), userInfo.getPasswordVer())) {
									
				userInfo.setPassword(userInfo.getPasswordNew());
				
				userInfo.setEmail(ContextHelper.getLoginId());
				userManager.updatePassword(userInfo);
			} else {
				return INPUT;
			}
			// remove authentication
			ContextHelper.removeAuthentication();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw e;
		}
		
		return SUCCESS;
	}
	
	private boolean validateChangingPassword(String passwordCur, String passwordNew, String passwordVer) {
		boolean res = true;
		
		if (StringUtils.isNotBlank(passwordNew) && StringUtils.isNotBlank(passwordVer)) {

			if (!ContextHelper.checkCurrentPass(passwordCur)) {
				model.setErrorMessage(getText("user.changepass.currentpass.wrong"));
				res = false;
			} else if (!passwordNew.equals(passwordVer)) {
				model.setErrorMessage(getText("user.changepass.confirmpass.wrong"));
				res = false;
			}
			
		} else {
			res = false;
		}
		return res;
	}
	
	/**
	 * Search User
	 */
	public String executeSearchUser() throws Exception {
		try {

			List<UserInfo> userInfoList = userManager.listUser();
			model.setUserInfoList(userInfoList);
			
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw e;
		}
		return SUCCESS;
	}
}